import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart';

import '../../../common/index.dart';
import 'message_bubble.dart';
import '../utils/image_cache_utils.dart';

class MessageList extends ConsumerWidget {
  const MessageList({
    super.key,
    required this.messages,
    required this.partnerUser,
    required this.onRefresh,
    required this.imageCacheUtils,
  });

  final List<MessageEntity> messages;
  final UserEntity? partnerUser;
  final VoidCallback onRefresh;
  final ImageCacheUtils imageCacheUtils;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return Container(
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height,
      color: Colors.black,
      child: RefreshIndicator(
        onRefresh: () async {
          onRefresh();
        },
        child: SingleChildScrollView(
          padding: EdgeInsets.symmetric(horizontal: 5.w),
          child: Column(
            children: [
              SizedBox(height: 20.h),
              ..._buildMessageList(ref),
              SizedBox(height: 120.h), // 为底部输入区域留出空间
            ],
          ),
        ),
      ),
    );
  }

  List<Widget> _buildMessageList(WidgetRef ref) {
    final currentUser = ref.read(currentUserProvider);
    if (currentUser == null || messages.isEmpty) {
      return [];
    }

    List<Widget> widgets = [];

    for (int i = 0; i < messages.length; i++) {
      final message = messages[i];
      final isCurrentUser = message.senderId == currentUser.id;

      // 检查是否需要显示时间
      bool showTime = false;
      if (i == 0) {
        showTime = true; // 第一条消息总是显示时间
      } else {
        final previousMessage = messages[i - 1];
        final timeDifference = message.timestamp.difference(
          previousMessage.timestamp,
        );
        showTime = timeDifference.inMinutes >= 5; // 超过5分钟显示时间
      }

      // 添加时间显示
      if (showTime) {
        widgets.add(_buildTimeDisplay(message.timestamp));
      }

      // 添加消息气泡
      widgets.add(_buildMessageBubble(message, isCurrentUser, currentUser));

      // 添加间距
      widgets.add(SizedBox(height: 10.h));
    }

    return widgets;
  }

  Widget _buildTimeDisplay(DateTime timestamp) {
    final timeFormat = DateFormat('HH:mm');
    final timeString = timeFormat.format(timestamp);

    return Container(
      margin: EdgeInsets.symmetric(vertical: 10.h),
      child: Center(
        child: Text(
          timeString,
          style: TextStyle(
            color: Colors.white.withValues(alpha: 0.6),
            fontSize: 12.sp,
            fontFamily: 'Roboto',
            fontWeight: FontWeight.w400,
          ),
        ),
      ),
    );
  }

  Widget _buildMessageBubble(
    MessageEntity message,
    bool isCurrentUser,
    UserEntity? currentUser,
  ) {
    return Align(
      alignment: isCurrentUser ? Alignment.centerRight : Alignment.centerLeft,
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 10.w),
        child: MessageBubble(
          message: message,
          isCurrentUser: isCurrentUser,
          currentUser: currentUser,
          partnerUser: partnerUser,
          imageCacheUtils: imageCacheUtils,
        ),
      ),
    );
  }
}
